package com.service.healthycode.service.impl;

import com.service.config.utils.*;
import com.service.healthycode.dao.JsonDataDao;
import com.service.healthycode.dao.TerminalListDao;
import com.service.healthycode.dto.Jsondata;
import com.service.healthycode.dto.NceUploadData;
import com.service.healthycode.entity.ApDetail;
import com.service.healthycode.entity.CloudCampusInfo;
import com.service.healthycode.entity.JsonData;
import com.service.healthycode.entity.TerminalList;
import com.service.healthycode.service.CloudCampusInfoService;
import com.service.healthycode.service.JsonDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 上报数据表(JsonData)表服务实现类
 *
 * @author makejava
 * @since 2021-10-21 14:14:35
 */
@Service("jsonDataService")
@Slf4j
public class JsonDataServiceImpl implements JsonDataService {
    @Resource
    private JsonDataDao jsonDataDao;
    @Resource
    TerminalListDao terminalListDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public JsonData queryById(String id) {
        return this.jsonDataDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<JsonData> queryAllByLimit(int offset, int limit) {
        return this.jsonDataDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param jsonData 实例对象
     * @return 实例对象
     */
    @Override
    public JsonData insert(JsonData jsonData) {
        this.jsonDataDao.insert(jsonData);
        return jsonData;
    }

    /**
     * 修改数据
     *
     * @param jsonData 实例对象
     * @return 实例对象
     */
    @Override
    public JsonData update(JsonData jsonData) {
        this.jsonDataDao.update(jsonData);
        return this.queryById(jsonData.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.jsonDataDao.deleteById(id) > 0;
    }

    @Override
    public void insertList(NceUploadData lbsEntity, CloudCampusInfo cloudCampusInfo) throws Exception {
        //查询所有未下线的终端
        List<TerminalList> terminals = terminalListDao.queryByStatus();

        List<TerminalList> terminalLists = new ArrayList<>();
        //将终端位置信息输出至csv文件，输出后关闭
        lbsEntity.getData().forEach(apUploadData -> {
            apUploadData.getTerminalList().forEach(terminalData -> {
                TerminalList terminallist = new TerminalList();
                terminallist.setId(IdUtil.getId().toString());
                terminallist.setTerminalMac(terminalData.getTerminalMac());
                terminallist.setApMac(apUploadData.getApMac());
                terminallist.setMacRssi(UuIDUtil.Random2(terminalData.getRssi()));
                terminallist.setTimestamp(String.valueOf(terminalData.getTimestamp()));
                terminallist.setUpdateTime(new Date());
                terminalLists.add(terminallist);
            });
        });
        if (terminals != null && terminals.size()>0)
        {
            if (terminalLists.size()<=0)
            {
                //数据库中所有终端都下线
                terminals.forEach(terminal-> {
                    try {
                        terminal.setUpdateTime(new Date());
                        terminal.setOffLineTime(new Date());
                        terminal.setStatus(true);
                        terminal.setTotalTime(DateUtil.getDateMin(DateUtil.datetoString(terminal.getOnLineTime()), DateUtil.datetoString(new Date())));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                });

                terminalListDao.offLine(terminals);
                return;
            }
            //新上传的数据中没有数据库中未下线的终端，这就表示该终端要下线啦
            List<TerminalList> collect1 = terminals.stream().filter(terminal -> !terminalLists.stream().map(TerminalList::getTerminalMac).collect(Collectors.toList()).contains(terminal.getTerminalMac())).collect(Collectors.toList());
            //新传递的数据中未下线的设备，表示在线上的终端现在还是在线上
            List<TerminalList> collect2 = terminalLists.stream().filter(terminal -> terminals.stream().map(TerminalList::getTerminalMac).collect(Collectors.toList()).contains(terminal.getTerminalMac())).collect(Collectors.toList());
            //新传递的数据中首次上线的设备，表示在数据库中没有上线的数据，即将要上线
            List<TerminalList> collect3 = terminalLists.stream().filter(terminal -> !terminals.stream().map(TerminalList::getTerminalMac).collect(Collectors.toList()).contains(terminal.getTerminalMac())).collect(Collectors.toList());
            if (collect1!= null && collect1.size()>0)
            {
                //下线
                collect1.forEach(c->{
                    try {
                        c.setOffLineTime(new Date());
                        c.setStatus(true);
                        c.setUpdateTime(new Date());
                        c.setTotalTime(DateUtil.getDateMin(DateUtil.datetoString(c.getOnLineTime()), DateUtil.datetoString(new Date())));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                });
                terminalListDao.offLine(collect1);
            }

            if (collect2!=null && collect2.size()>0)
            {
                //保持，修改时间
            }

            if (collect3!=null && collect3.size()>0)
            {
                //上线
                collect3.forEach(c->{
                    c.setStatus(false);
                    c.setUpdateTime(new Date());
                    c.setOnLineTime(new Date(Long.parseLong(c.getTimestamp())));
                });
                terminalListDao.insertBatch(collect3);
            }
        }else if (terminalLists.size()>0){
            //所有终端上线
            terminalLists.forEach(terminal->{
                terminal.setStatus(false);
                terminal.setUpdateTime(new Date());
                terminal.setOnLineTime(new Date(Long.parseLong(terminal.getTimestamp())));
            });
            terminalListDao.insertBatch(terminalLists);
            return;
        }
    }
}
